package com.jms.rabbitmq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * 发送消息
 *
 * @param <T>
 */
@Component
@ConditionalOnProperty(name = "config.rabbitmq.enable", havingValue = "true")
public class Sender<T> implements RabbitTemplate.ConfirmCallback {

    private final Logger log = LoggerFactory.getLogger(Sender.class);

    /***
     * ConditionOnMissingBean,如果用户没有创建该类的bean，则框架会创建
     * 用户可以自定义其配置，这样做出的框架非常好用
     */
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
    }

    /**
     * 发送消息
     *
     * @param exchange   交换机名称
     * @param routingKey 路由关键字 路由是队列和交换机连接的纽带
     * @param object     发送的消息内容
     */
    public void send(String exchange, String routingKey, T object) {
        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
        //log.info("开始发送消息: " + JsonMapper.toJsonString(object));
        rabbitTemplate.convertAndSend(exchange, routingKey, object, correlationId);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        if (b) {
            log.info("消息发送成功，msgId: {}", correlationData.getId());
        } else {
            log.error("消息发送失败：" + s);
            throw new RuntimeException("消息发送失败：" + s);
        }

    }
}
